package sjtu.FaceRecognition;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

/**
 * 
 * @author Frank, Chen
 * This class is utility used for network interaction and related IO operation.
 *
 */
public class NetworkUtil {
	
	private static final String USER_NAME_FLAG = "pictureInfo.userName=";
	private static final String TIME_FLAG = "pictureInfo.time=";
	private static final String FILE_TYPE_FLAG = "pictureInfo.fileType=";
	private static final String ORIENTATION_FLAG = "pictureInfo.orientation=";
	private static final String PROXIMITY_FLAG = "pictureInfo.proximity=";
	private static final String REAL_TIME_FLAG = "pictureInfo.realTime=";
	private static final String TAG = "network util";
	
	/**
	 * 
	 * @param pic_data
	 * @return result message from server(Json is chosen)
	 */
	public static String getExpressionResultFromServer(byte[] pic_data) {
		if (CommonUtil.DEBUG_LOG) {
			Log.e(TAG, "network send pic size is " + pic_data.length);
		}
		try {
			String timeStamp = CommonUtil.getCurrentTimeString();
			String requestUrl = CommonUtil.SERVER_URL + CommonUtil.SERVER_PATH
					+ "?" + USER_NAME_FLAG + CommonUtil.myUsername + "&"
					+ TIME_FLAG + timeStamp + "&" + FILE_TYPE_FLAG
					+ CommonUtil.PIC_FILE_TYPE + "&" + ORIENTATION_FLAG
					+ CameraUtil.getPhoneOrientation() + "&" + PROXIMITY_FLAG
					+ CameraUtil.getProximity() + "&" + REAL_TIME_FLAG + CommonUtil.IS_REAL_TIME;
			String picFileName = "IMG_" + timeStamp + "." + CommonUtil.PIC_FILE_TYPE;
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST"); 
			conn.setDoOutput(true);
			
			//perform just like browser does when uploading files, using multipart/form-data
			StringBuffer sb = new StringBuffer();
			sb.append("--");  
            sb.append(CommonUtil.BOUNDRAY);  
            sb.append("\r\n");  
            sb.append("Content-Disposition: form-data; name=\"pictureInfo.file\"; filename=\"" + picFileName + "\"\r\n");
            sb.append("Content-Type: application/octet-stream\r\n\r\n");
            byte[] start_data = sb.toString().getBytes();
            
            byte[] end_data = ("\r\n--" + CommonUtil.BOUNDRAY + "--\r\n").getBytes();
            
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + CommonUtil.BOUNDRAY);  
            conn.setRequestProperty("Content-Length", String.valueOf(start_data.length + pic_data.length + end_data.length));
            conn.setConnectTimeout(CommonUtil.NETWORK_TIME_OUT);
            
            BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream());
            bos.write(start_data);
            bos.write(pic_data);
            bos.write(end_data);
            bos.flush();
            bos.close();
            
            conn.connect();
            int statusCode = conn.getResponseCode();
            if (CommonUtil.DEBUG_LOG) {
            	Log.e(TAG, "status code is " + statusCode);
            }
            if (statusCode == CommonUtil.REQUEST_SUCCESS_CODE) {
            	return getJsonContent(conn.getInputStream());
            }
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}
		return null;
	}
	
	/**
	 * 
	 * @param is
	 * @return json content from input stream
	 */
	private static String getJsonContent(InputStream is) {
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuilder builder = new StringBuilder();
		String line = null;
    	try {
			while((line = br.readLine()) != null) {
				builder.append(line);
			}
			br.close();
	    	is.close();
	    	String result = builder.toString();
			return result;
		} catch (IOException e) {
		}
    	return null;
    	
	}
	
}
